// 极简 WebRTC 信令服务（开发用）
// 启动：
//   1) npm i ws -D   或  npm i ws
//   2) node dev-signal-server.js
// 访问：ws://localhost:8081?roomId=xxx

const WebSocket = require('ws')
const url = require('url')
const PORT = process.env.SIGNAL_PORT ? parseInt(process.env.SIGNAL_PORT, 10) : 8081

// roomId -> Set<Client>
const rooms = new Map()

function joinRoom(roomId, ws) {
  if (!rooms.has(roomId)) rooms.set(roomId, new Set())
  rooms.get(roomId).add(ws)
  ws._roomId = roomId
}
function leaveRoom(ws) {
  const roomId = ws._roomId
  if (!roomId) return
  const set = rooms.get(roomId)
  if (set) {
    set.delete(ws)
    if (set.size === 0) rooms.delete(roomId)
  }
}

const wss = new WebSocket.Server({ port: PORT }, () => {
  console.log(`Signaling server listening ws://localhost:${PORT}  (query: ?roomId=xxx)`) 
})

wss.on('connection', (ws, req) => {
  const { query } = url.parse(req.url, true)
  const roomId = query.roomId || ''
  if (roomId) joinRoom(roomId, ws)

  ws.on('message', (data) => {
    let msg = {}
    try { msg = JSON.parse(data) } catch (e) { return }
    const r = msg.roomId || ws._roomId
    if (!r) return
    const set = rooms.get(r)
    if (!set) return
    set.forEach((cli) => {
      if (cli !== ws && cli.readyState === WebSocket.OPEN) {
        cli.send(JSON.stringify(msg))
      }
    })
  })

  ws.on('close', () => leaveRoom(ws))
  ws.on('error', () => leaveRoom(ws))
})
